<style scoped>
  .user-search {
    margin-top: 20px;
  }
</style>

<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>班次管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
      </el-form-item>
      <el-form-item label="" v-for="(filter, index) in searchParams.filters" :key="index">
        <el-input size="small" v-model="filter.fieldValue" v-bind:fieldName="filter.fieldName" v-if="filter.showAble"
                  v-bind:fieldValue="filter.fieldValue" v-bind:compare="filter.compare" :disabled="filter.readonly"
                  @keyup.enter.native="search"
                  :placeholder="filter.placeholder" :readonly="filter.readonly" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table size="small" :data="list" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中"
              style="width: 100%;" :header-row-style="{width: '100%', color: 'darkorange'}">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column align="center" prop="name" label="班次名称">
      </el-table-column>
      <el-table-column align="center" prop="surveyName" label="关联问卷">
      </el-table-column>
      <el-table-column align="center" prop="shiftDate" label="班次日期">
      </el-table-column>
      <el-table-column align="center" prop="startTime" label="开始时间">
      </el-table-column>
      <el-table-column align="center" prop="endTime" label="结束时间">
      </el-table-column>
      <el-table-column align="center" prop="address" label="举办地点">
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="showApplyList(scope.$index, scope.row)">查看申请</el-button>
          <el-button size="mini" type="danger" @click="deleteItem(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageParams" @callFather="callFather"/>

    <!-- 新增界面 -->
    <el-dialog :title="editTitle" :visible.sync="editFormVisible" width="70%"
               :close-on-click-modal="false" @click='closeDialog("edit")' top="10vh">
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="所属公司" prop="companyName">
          <el-input size="small" disabled v-model="editForm.companyName" placeholder="请输入所属公司"/>
        </el-form-item>

        <el-form-item label="班次名称" prop="name">
          <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="请输入简短的名称"/>
        </el-form-item>

        <el-form-item label="所属问卷" prop="surveyName">
          <el-autocomplete style="width: 100%" size="small" v-model="editForm.surveyName"
                           :fetch-suggestions="querySearchAsync" @select="handleSelect" auto-complete="off"
                           placeholder="请输入问卷名称"/>
        </el-form-item>
        <el-form-item label="选择日期" prop="shiftDate">
          <el-date-picker
            v-model="editForm.shiftDate"
            align="right"
            type="datetime"
            value-format="yyyy-MM-dd 00:00:00"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="班次时间" required>
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-time-select
                placeholder="开始时间"
                v-model="editForm.startTime"
                :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '24:00'}">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">至</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-time-select
                placeholder="结束时间"
                v-model="editForm.endTime"
                :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '24:00',
                minTime: editForm.startDate
              }">
              </el-time-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="班次地点" prop="address">
          <el-input size="small" v-model="editForm.address" auto-complete="off" placeholder="请输入班次地址"/>
        </el-form-item>

        <el-form-item label="请选择队列" prop="queueId">
          <el-select style="width: 50%" v-model="editForm.queueId" placeholder="请选择队列">
            <el-option :label="item.name" :value="item.id"
                       v-for="(item, index) in queueNames" :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitAddForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>


    <!-- 查看班次申请列表 -->
    <el-dialog :title="'班次申请列表'" :visible.sync="showApplyListSync" width="70%"
               :close-on-click-modal="false" @click='closeDialog("edit")' top="10vh">
      <el-empty v-if="!applyList || applyList.length === 0" description="暂无数据"></el-empty>

      <el-table v-if="applyList && applyList.length > 0" size="small" :data="applyList"
                highlight-current-row v-loading="false" border element-loading-text="拼命加载中"
                style="width: 100%;" :header-row-style="{width: '100%', color: 'darkorange'}"
                >
        <el-table-column prop="username" label="申请人">
        </el-table-column>
        <el-table-column prop="updateAt" label="申请时间">
        </el-table-column>
        <el-table-column prop="result" label="状态" width="180">
          <template slot-scope="scope">
            <span>{{scope.row.result | applyRecordFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" :disabled="scope.row.result !== 0" @click="pass(scope.$index, scope.row)">同意</el-button>
            <el-button size="mini" :disabled="scope.row.result !== 0" type="danger" @click="unpass(scope.$index, scope.row)">驳回</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>
  </div>
</template>

<script>
  import Pagination from "../../../components/Pagination";
  import {queueAll, recordList, recordUpdate, shiftDelete, shiftList, shiftSave, surveyList} from "../../../api/baseMG";
  import {getStore} from "../../../utils/util";

  export default {
    data() {
      return {
        list: [],
        applyList: [],
        loading: false,
        editTitle: '新增',
        queueNames: [],
        editFormVisible: false,
        showApplyListSync: false,
        editForm: {},
        rules: {
          surveyName: [
            {required: true, message: '请选择问卷', trigger: 'blur'}
          ],
          shiftDate: [
            {required: true, message: '请选择班次日期', trigger: 'blur'}
          ],
          startDate: [
            {required: true, message: '请选择班次开始时间', trigger: 'blur'}
          ],
          endDate: [
            {required: true, message: '请选择班次结束时间', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入班次名称', trigger: 'blur'}
          ],
          queueId: [
            {required: true, message: '请选择队列', trigger: 'blur'}
          ]
        },
        // 分页参数
        pageParams: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
        searchParams: {
          page: 1,
          perPage: 10,
          filters: [
            {
              showAble: false,
              readonly: true,
              placeholder: "默认",
              fieldName: "companyId",
              compare: "=",
              fieldValue: getStore("userInfo").companyId
            },
            {
              showAble: true,
              readonly: false,
              placeholder: "班次名称",
              fieldName: "name",
              compare: "like",
              fieldValue: ""
            }
          ],
          isLock: ''
        },
        pickerOptions: {
          disabledDate(time) {
            return (time.getTime() + 3600 * 1000 * 24) <= Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '明天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '后天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 2);
              picker.$emit('pick', date);
            }
          }]
        }
      }
    },
    created() {
      this.search();
      this.initQueueNames();
    },
    filters: {
      applyRecordFilter(data) {
        if(data === 0) {
          return '未审核';
        }
        if(data === 1) {
          return '通过';
        }
        if(data === 2) {
          return '驳回';
        }
      }
    },
    components: {
      Pagination
    },
    methods: {
      initQueueNames() {
        let that = this;
        queueAll().then(resp => {
          for (let i = 0; i < resp.data.length; i++) {
            let d = resp.data[i];
            that.queueNames.push({id: d.id, name: d.queueName})
          }
        })
      },
      pass(index, row) {
        row.result = 1;
        recordUpdate(row).then(resp => {
          if(resp.success) {
            this.$message.success(resp.msg);
          } else {
            this.$message.error(resp.msg);
          }
        })

      },
      unpass(index, row) {
        row.result = 2;
        recordUpdate(row).then(resp => {
          if(resp.success) {
            this.$message.success(resp.msg);
          } else {
            this.$message.error(resp.msg);
          }
        })
      },
      handleSelect(item) {
        this.editForm.surveyId = item.id;
        this.editForm.surveyName = item.name;
      },
      querySearchAsync(queryString, cb) {
        surveyList({
          page: 1,
          perPage: 10,
          filters: [
            {fieldName: "companyId", compare: "=", fieldValue: getStore("userInfo").companyId},
            {fieldName: "name", compare: "like", fieldValue: queryString},
            {fieldName: "state", compare: "=", fieldValue: 2}
          ],
          isLock: ''
        }).then(resp => {
          this.selectProjectList = resp.data.list;
          for (let i = 0; i < this.selectProjectList.length; i++) {
            this.selectProjectList[i].value = this.selectProjectList[i].name;
          }
          cb(this.selectProjectList);
        })
      },
      submitAddForm(params) {
        console.log(params)
        this.$refs[params].validate(valid => {
            if (valid) {
              shiftSave(this.editForm).then(resp => {
                if (resp.success) {
                  this.$message({
                    type: 'success',
                    message: resp.msg
                  });
                  this.search();
                  this.editFormVisible = false;
                }
              })
            }
          }
        );
      },
      closeDialog(data) {
        this.editFormVisible = false;
      },
      showApplyList(index, row) {
        this.showApplyListSync = true;
        recordList(
          {
            page: 1,
            perPage: 10,
            filters: [
              {
                showAble: true,
                readonly: false,
                placeholder: "班次主键",
                fieldName: "shiftId",
                compare: "=",
                fieldValue: row.id
              }]
          }
        ).then(resp => {
          this.applyList = resp.data.list;
        })
      },
      deleteItem(index, row) {
        this.$confirm('确定要删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          shiftDelete(row.id).then(res => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: res.msg
              });
              this.search(this.formInline)
            } else {
              this.$message({
                type: 'info',
                message: res.msg
              })
            }
          })
            .catch(err => {
              this.loading = false;
              this.$message.error('删除失败，请稍后再试！')
            })
        })
          .catch(err => {
            console.error(err);
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },
      handleAdd() {
        this.editFormVisible = true;
        this.editTitle = "新增班次";
        this.editForm = {
          shiftDate: "",
          autoCall: 1,
          companyId: getStore("userInfo").companyId,
          companyName: getStore("userInfo").company,
          surveyId: null,
          surveyName: '',
          name: "",
          startTime: "",
          endTime: "",
          projectId: 1
        };
      },
      search() {
        this.getList(this.searchParams);
      },
      getList(params) {
        this.loading = true;
        shiftList(params).then(resp => {
          if (resp.success) {
            this.loading = false;
            this.list = resp.data.list;
            this.pageParams.currentPage = resp.data.pageNum;
            this.pageParams.pageSize = resp.data.pageSize;
            this.pageParams.total = resp.data.total;
          }
        }).catch(e => {
          this.loading = false;
        })
      },
      // 分页插件事件
      callFather(param) {
        this.searchParams.page = param.currentPage;
        this.searchParams.perPage = param.pageSize;
        this.getdata(this.searchParams);
      }
    }
  }
</script>
